<!doctype html>
<html lang="en">
<head>
    @include('web.layout.head')
    <link rel="stylesheet" href="{{asset('/css/plugins/jQueryUI/jquery-ui-1.11.4.min.css')}}">
    <link rel="stylesheet" href="{{mix('/css/web/inc/ui-autocomplete.css')}}">
    <link rel="stylesheet" href="{{mix('/css/web/user/prove_release.css')}}">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    @include('UEditor::head')
</head>
<body>
@include('web.layout.header')
@include('web.layout.user_tab')
<div class="base_member_content">
    <div class="w1200">

        @include('web.layout.seller_nav')
        <div class="nav_right flr">
            <form action="{{$request_url}}" method="post" id="frm-post">
              @if(isset($type) && $type == 'put')
                                {{method_field("PUT")}}
                            @endif
            <input type="hidden" name="first_cat" value="{{old('first_cat')}}">
            <input type="hidden" name="second_cat" value="{{old('second_cat')}}">
            <input type="hidden" name="third_cat" value="{{old('third_cat')}}">



            <div class="marryreal">
                <div class="name"><span class="goodsfabu">商品详情</span>
                    <div class="steps">
                        <span class="xuanz">1.选择类目</span>
                        <span class="xuanz">2.填写商品详情</span>
                        <span class="xuanzno">3.提交成功</span>
                    </div>
                </div>
                <div class="clear"></div>
                 <div class="nowxz">
                    <span>您当前选中的类目：</span>
                    <span>{{old('c1')}}</span>
                    &gt;<span>{{old('c2')}}</span>
                    &gt;<span>{{old('c3')}}</span>
                    @if(old('id'))
                    <span class="reset"><a href="/member/seller/product/create?step=cate&id={{old('id')}}" rel="nofollow">(返回重选类目)</a></span>
                    @else
                     <span class="reset"><a href="/member/seller/product/create?step=cate" rel="nofollow">(返回重选类目)</a></span>
                    @endif
                </div>
                <div class="name">基本信息</div>
                <div class="content" style="min-height: auto">
                    <div class="hang">
                        <div class="name"><span class="red">*</span>商品标题</div>
                        <div class="nameright">
                            <input value="{{old('product_desc')}}" type="text" name="product_desc" class="goodstitle" onkeyup="words_deal(this, 60);" placeholder="请填写品牌、商品名称、商品型号、商品特征及具体描述"> <span class="textCount">0</span><span>/60</span><span class="maxtitle">超过最大可输入字数</span>
                            @if($errors->has('name'))
<div class="jm_error" id="cptitle">商品标题必填</div>
@endif
                        </div>
                    </div>

                    <div class="hang top">
                        <div class="name">商品属性</div>
                        <div class="nameright isjiaruh">
                            <div class="rowh">
                                <div class="row_name "><span class="red">*</span>商品名称</div>
                                <div class="row_right">
                                    <input value="{{old('name')}}" type="text" name="name" placeholder="请输入商品名称" class="goodsname">

                                </div>

                            </div>
                           @if($errors->has('name'))
                            <div class="jm_error fl" id="name">商品名称必填</div>
                            @endif
                            <div class="rowh">
                                <div class="row_name ">自定义分类</div>
                                <div class="row_right">
                                <select class="custom_cate" name="custom_cate">
                                @foreach(old('categories') as $cate)
                                 <option value="{{$cate['id']}}" @if(old('custom_cate')== $cate['id'] ) )  selected="selected" @endif>{{$cate['name']}}</option>
                                @endforeach
                                </select>
                                </div>
                            </div>
                            <div class="rowh" style="margin-bottom: 10px;">
                                <div class="row_name" ><span class="red">*</span>品牌</div>
                                <div class="row_right brandsxz" id="brands">
                                 <?php
                                    $brand_id = old('brand_id');
                                    $brands = old('brands');
                                    $brand_name = "";
                                    if($brands){
                                        foreach($brands as $b){
                                            if($b['id'] == $brand_id){
                                                $brand_name = $b['name'];
                                            }
                                        }

                                    }

                                    ?>
                                    <input type="hidden" name="brand_id" value="{{ old('brand_id') }}">
                                    <input type="text" name="brand_name" placeholder="请选择品牌"  value="@if($brand_name){{$brand_name}}@endif">

                                    <!-- <div class="qxzbrands">@if($brand_name) {{$brand_name}} @else 请选择品牌 @endif</div> -->

                                     @if($errors->has('brand_id'))
                                    <p class="jm_error fl" id="cpbrangs" style="line-height: normal;">请选择品牌</p>
                                    @endif
                                    <div class="brandsxuanze " style="display: none">
                                        <div class="sort_box">
                                            <div class="sort_list">
                                            	@foreach(old('brands') as $brand)
                                                    <div data-id="{{$brand['id']}}" class="num_name">{{$brand['name']}}</div>
                                                @endforeach
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="rowh">
                                <div class="row_name "><span class="red">*</span>型号</div>
                                <div class="row_right">
                                    <input value="{{ old('model') }}" type="text" name="model" placeholder="请输入商品型号" class="xinghao">
                                </div>
                            </div>
                             @if($errors->has('model'))
                            <div class="jm_error fl" style="" id="cpxinghao">请输入型号</div>
                            @endif
                        <!--   <div class="rowh">
                                <div class="row_name">关键词</div>
                                <div class="row_right keyword_box">
                                    <ul class="fl">
                                        <li><input value="{{ old('keywords') }}" type="text" name="keywords" class="fl keywordss"></li>
                                    </ul>

                                </div>
                            </div>-->

                              @if(is_array(old('attrs')))
                        @foreach(old('attrs') as $attr)
                        @if($attr['is_sku'] == 0)
                             <div class="rowh">
                             <div class="row_name">{{$attr['name']}}</div>
                            <div class="row_right">
<!--                                     <ul class="fl"> -->
<select class="cpu_type">
<option value="-">请选择</option>
                                     @if(isset($attr['values']) && $attr['values'] )
                                     <?php
                                     $e_attrs = explode(";",old('custom_attrs'));
                                     ?>
                            @foreach($attr['values'] as $k=>$val)
                            <?php
                            if( in_array($attr['attribute_id'].':'.$attr['name'].','.$k.':'.$val ,$e_attrs)){
                                //$is_sel = "checked='checked'";
                                $is_sel = "selected='selected'";
                            }else{
                                $is_sel = "";
                            }
                            ?>
                            <option data-aid="{{$attr['attribute_id']}}" {{$is_sel}} data-aname="{{$attr['name']}}"  name="cattrs" data-name="{{$val}}" class="cattrs fl keywords" value="{{$k}}">{{$val}}</option>
<!--                                         <li class="cpu_type">   <input value="{{$k}}"  data-aid="{{$attr['attribute_id']}}" {{$is_sel}} data-aname="{{$attr['name']}}" type="checkbox" name="cattrs" data-name="{{$val}}" class="cattrs fl keywords">{{$val}}</li> -->
                                          @endforeach
                            @endif
                            </select>
<!--                                     </ul> -->
                                </div>
                            </div>
                            @endif
                           @endforeach
                           @endif


                        </div>
                    </div>
                </div>
                <div class="content" style="min-height: auto">
                    <div class="hang">
                        <div class="name namefilee" ><span class="red">*</span>列表图</div>
                        <div class="nameright">
                            <div class="modify fl fontsize" >
                                <div class="imgbox">
                                    <div class="list_image fl">
                                    <?php if(old('cover_image')){?>
                                		<div class="upload-img-item">
                                            <img src="/img/web/user/close.png" class="icon-colse" >
                                			<img src="{{old('cover_image')}}"  class="shangchuan btn_listimg" data-id="0"
                                            style="cursor: pointer">
                                		</div>
                                		<input type="hidden" name="cover_image" value="{{old('cover_image')}}">
                                	<?php } else {?>
                                        <div class="upload-img-item">
                                            <img src="{{asset('/img/web/user/fileOne.png')}}"  class="shangchuan btn_listimg" data-id="0" title="点此上传商品图片" style="cursor: pointer">
                                        </div>
                                        <input type="hidden" name="cover_image">
                                        <?php } ?>
                                        <img src="{{asset('/img/web/user/fileOne.png')}}" style="display: none" class="default_img" />
                                	</div>
                                </div>
                            </div>
                        </div>
                        @if($errors->has('cover_image'))
                        <div class="jm_error fl" id="err_listimg">请上传列表图</div>
                        @endif
                    </div>
                    <div class="hang top">
                        <div class="name namefilee" ><span class="red">*</span>主图(详情页)</div>
                        <div class="nameright">
                            <div class="modify fl fontsize" >
                                <div class="imgbox">


                                		    <?php

    		    if(!is_array(old('images'))){
    		        $images = json_decode(old('images'),true);
    		    }else{
    		        $images = old('images');
    		    }

    		    if(!is_array($images)){
                    $images = old('images');
                    if($images){
                     echo '<div class="upload-img-item"><img src="/img/web/user/close.png" class="icon-colse" >
                                			<img src="'.$images.'"  class="shangchuan">
                                		</div>';
                    }
                }else{
                    foreach($images as $img){
                        echo '<div class="upload-img-item"><img src="/img/web/user/close.png" class="icon-colse" >
                                			<img src="'.$img.'"  class="shangchuan">
                                		</div>';
                    }
                }
                ?>


                                    <img src="{{asset('/img/web/user/file.png')}}"    title="点此上传商品图片" class="shangchuan btn_detailimg" style="cursor: pointer; " id="upload-img" data-id="1"/>
                                </div>
                            </div>
                        </div>
                        @if($errors->has('images'))
                        <div class="jm_error fl" id="err_image">请上传主图</div>
                        @endif
                    </div>
                    <div class="hang top">
                        <div class="name"><span class="red">*</span>商品详情</div>
                        <div class="nameright">
                            <script id="editor_id" name="product_detail"  style="min-height:300px;" type="text/plain"> {!! old('product_detail') !!} </script>
                             @if($errors->has('product_detail'))
                            <div class="jm_error fl" id="err_content">商品详情必填</div>
                            @endif
                        </div>
                    </div>
                    <div class="hang top">
                        <div class="name"><span class="red">*</span>产地</div>
                        <div class="nameright2">
                            <div class="namedt" style="position: relative;">
                                <input value="{{old('place_origin')}}" type="text" name="place_origin" class="minorder placeOrigin" id="selected_city"  autocomplete="off" data-region-id="">
                                @include('web.layout.city_placeOrigint')
                            </div>
                             @if($errors->has('place_origin'))
                            <div class="jm_error fl" id="err_placeOrigin">产地必填</div>
                            @endif
                        </div>
                    </div>
                    <div class="hang top">
                        <div class="name"><span class="red">*</span>计量单位</div>
                        <div class="nameright">
                            <div class="namedt unitlist">
                                <label><input   @if(old('unit')==1 || !old('unit') ) ) checked="checked" @endif class="unit" type="radio" name="unit" value="1"/>个</label>
                                <label><input @if(old('unit')==2) ) checked="checked" @endif class="unit" type="radio" name="unit" value="2"/>台</label>
                                <label><input @if(old('unit')==3) ) checked="checked" @endif class="unit" type="radio" name="unit" value="3"/>件</label>
                                <label><input @if(old('unit')==4) ) checked="checked" @endif class="unit" type="radio" name="unit" value="4"/>箱</label>
                                <label><input @if(old('unit')==5) ) checked="checked" @endif class="unit" type="radio" name="unit" value="5"/>米</label>
                                <label><input @if(old('unit')==6) ) checked="checked" @endif class="unit" type="radio" name="unit" value="6"/>对</label>
                                 <label><input @if(old('unit')==7) ) checked="checked" @endif class="unit" type="radio" name="unit" value="7"/>根</label>
                                <label><input @if(old('unit')==8) ) checked="checked" @endif class="unit" type="radio" name="unit" value="8"/>支</label>
                                <label><input @if(old('unit')==9) ) checked="checked" @endif class="unit" type="radio" name="unit" value="9"/>100米</label>
                                <label><input @if(old('unit')==10) ) checked="checked" @endif class="unit" type="radio" name="unit" value="10"/>套</label>
                            </div>
                        </div>
                    </div>
                    <div class="hang top">
                        <div class="name"><span class="red">*</span>发货周期</div>
                        <div class="nameright">
                            <div class="namedt">
                                <select class="deliveryCycle" name="delivery_time">
                                    <option value="1" @if(old('delivery_time')==1) )  selected="selected" @endif >3-5个工作日</option>
                                    <option value="2" @if(old('delivery_time')==2) )  selected="selected" @endif>6-9个工作日</option>
                                    <option value="3" @if(old('delivery_time')==3) )  selected="selected" @endif>10-15个工作日</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="hang top">
                        <div class="name"><span class="red">*</span>保质期</div>
                        <div class="nameright">
                            <div class="namedt">
                                <select class="keepTime" name="guarantee_period">
                                    <option value="1" @if(old('guarantee_period')==1) )  selected="selected" @endif>1年</option>
                                    <option value="2" @if(old('guarantee_period')==2) )  selected="selected" @endif>2年</option>
                                    <option value="3" @if(old('guarantee_period')==3) )  selected="selected" @endif>3年</option>、
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="hang top">
                        <div class="name"><span class="red">*</span>是否优惠促销</div>
                        <div class="nameright">
                            <div class="namedt promotionlist">
                                <label><input class="promotion" checked="checked" type="radio" name=is_onsales value="1" @if(old('is_onsales')==1) ) checked="checked" @endif/>是</label>
                                <label><input class="promotion" type="radio" name="is_onsales" value="0" @if(old('is_onsales')==0) ) checked="checked" @endif/>否</label>
                            </div>
                        </div>
                    </div>
                    <div class="hang top">
                        <div class="name"><span class="red">*</span>是否推荐</div>
                        <div class="nameright">
                            <div class="namedt recommendlist">
                                <label><input class="recommend" checked="checked" type="radio" name="is_recommend" value="1" @if(old('is_recommend')==1) ) checked="checked" @endif />是</label>
                                <label><input class="recommend" type="radio" name="is_recommend" value="0" @if(old('is_recommend')==0) ) checked="checked" @endif  / >否</label>
                            </div>
                        </div>
                    </div>
                    <div class="hang top">
                        <div class="name"><span class="red">*</span>是否热门商品</div>
                        <div class="nameright">
                            <div class="namedt hotlist">
                                <label><input class="hot" checked="checked" type="radio" name="is_hot" value="1" @if(old('is_hot')==1) ) checked="checked" @endif/>是</label>
                                <label><input class="hot" type="radio" name="is_hot" value="0" @if(old('is_hot')==0) ) checked="checked" @endif />否</label>
                            </div>
                        </div>
                    </div>

                    <div class="hang top">
                        <div class="name"><span class="red">*</span>商品规格</div>
                        <div class="skuright">
                        <?php $exit_sku = false;?>
                        @if(is_array(old('attrs')))
                        @foreach(old('attrs') as $attr)
                        @if($attr['is_sku'] == 1 && isset($attr['values']) && $attr['values'])
                            <ul class="SKU_TYPE">
                                <li is_required='0' propid='{{$attr['attribute_id']}}' sku-type-name="{{$attr['name']}}">{{$attr['name']}}：</li>
                            </ul>
                            <ul class="sku_value_ul">
                            <?php
                            $exit_sku = true;
                            $attr_ids = json_decode(old('attr_ids'),true);
                            $not_select = "";
                            if(!$attr_ids){
                                $attr_ids = [];
                            }else{
                                $not_select = "disabled='disabled'";
                            }
                            ?>
                            @if(isset($attr['values']) && $attr['values'] )
                            @foreach($attr['values'] as $k=>$val)
                                <li><label class="fl"><input type="checkbox"  class="sku_value" propvalid='{{$k}}'  propid='{{$attr['attribute_id']}}' value="{{$val}}"  <?php   if(in_array($k, $attr_ids)){?>  checked="checked"  <?php }?>/>{{$val}}</label>
                                </li>
                            @endforeach
                            @endif
                            @if(!old('id'))
                                <li>
                                    <input type="text" value="" class="add_sku_value_val fl">
                                    <a class="add_sku_value fl" data-id="{{$attr['attribute_id']}}">添加</a>
                                </li>
                                 @endif
                            </ul>
                            <div class="clear"></div>
                            @endif
                           @endforeach
                           @endif
                            <div id="skuTable">
                            <?php if(!$exit_sku){?>
                            	<table class="skuTable">
                                	<tbody>
                                    	<tr>
                                        	<th width="70">价格(元)</th>
                                        	<th width="70">促销价(元)</th>
                                        	<th width="70">库存数</th>
                                        	<th width="150">商家编码</th>
                                        	<th width="70">运费</th>
                                    	</tr>
                                    	<tr propvalids="" propids="" propvalnames="" propnames="" class="sku_table_tr">
                                        	<td><input type="text" class="setting_sku_price"  value="" onkeyup="onlyNumber(this)" onblur="onlyNumber(this)" ></td>
                                        	<td><input type="text" class="setting_sku_originalprice" value="" onkeyup="onlyNumber(this)" onblur="onlyNumber(this)" ></td>
                                        	<td><input type="text" class="setting_sku_stock" value="" onkeyup="onlyNumber(this)" onblur="onlyNumber(this)"></td>
                                        	<td><input type="text" class="setting_sku_coding" value=""  ></td>
                                        	<td><input type="text" class="setting_sku_freight" value="" onkeyup="onlyNumberHaveZero(this)" onblur="onlyNumberHaveZero(this)" ></td>
                                        	<input type="hidden" class="setting_sku_id" value="">
                                    	</tr>
                                	</tbody>
                            	</table>
                            	<?php }?>
                            </div>
                            <div class="jm_error fl" id="err_sku"></div>
                        </div>
                    </div>
                    <div class="hang top">
                        <div class="name">售后服务</div>
                        <div class="nameright">
                            <div class="namedt servicelist">
                            <?php
                                $sale_arr = explode(",",old('after_sale_guarantee'));
                            ?>
                                <label><input class="service" type="checkbox" name="guarantee" value="1" @if(in_array("1",$sale_arr)) checked="checked" @endif />提供发票</label>
                                <label><input class="service" type="checkbox" name="guarantee" value="2" @if(in_array("2",$sale_arr))  checked="checked" @endif />保修服务</label>
                                <label><input class="service" type="checkbox" name="guarantee" value="3" @if(in_array("3",$sale_arr))  checked="checked" @endif/>退货承诺：诺存在质量问题或与描述不符，本店将主动提供退货服务并承担来回邮费</label>
                            </div>
                        </div>
                    </div>

                    <div class="hang top">
                        <div class="name">橱窗推荐</div>
                        <div class="nameright">
                            <div class="namedt windowlist">
                                <label><input class="window" type="checkbox" name="is_cupboard"  @if(old('is_cupboard') == 1) checked="checked"   @endif  value="1"  @if(old('cupboards') > 14 ) disabled='disabeld' @endif />是</label>
                                <span>您的橱窗使用情况：共<font>【15】</font>个，已用【{{old('cupboards')}}】个。</span>
                            </div>
                        </div>
                    </div>
                </div>
                {{csrf_field()}}
                <input type="hidden" id="skus" name="skus" value="{{old('skus')}}">
                <input type="hidden" id="after_sale_guarantee" name="after_sale_guarantee" value="">
                <input type="hidden" id="is_for_sale" name="is_for_sale" value="0">

                <?php
                if(!is_array(old('images'))){
                    $images = json_decode(old('images'),true);
                }else{
                    $images = old('images');
                }


                if(!is_array($images)){
                    $images = old('images');
                    if($images){
                        echo '<input type="hidden" name="images[]" value="'.$images.'" class="j-hid-images">';
                    }
                }else{
                    foreach($images as $img){
                        echo '<input type="hidden" name="images[]" value="'.$img.'" class="j-hid-images">';
                    }
                }
                ?>
                <input type="hidden"  value="" name="custom_attrs" id="custom_attrs" />
                <input type="submit" data-type="0" class="drafts" value="保存至草稿箱">
                <input type="submit" data-type="1" class="tijiao" value="发布商品">
            </div>
            </form>
        </div>
    </div>
</div>
<form id="uploadForm" action="{{url('uploads/images')}}" method="post">
    {{csrf_field()}}
    <input style="display: none;" name="image" type="file" class="inputFile" />
</form>
@include('web.layout.footer')
<script src="{{mix('/js/web/image/uploadPreview.min.js')}}"></script>
<script src="{{mix('/js/web/user/jquery.charfirst.pinyin.js')}}"></script>
<!-- <script src="{{mix('/js/web/user/sort.js')}}"></script> -->
<script src="{{mix('/js/web/inc/fileUpload.js')}}"></script>
<script type="text/javascript">
function onlyNumber(obj) {
    //得到第一个字符是否为负号
    var t = obj.value.charAt(0);
    //先把非数字的都替换掉，除了数字和.
    obj.value = obj.value.replace(/[^\d\.]/g, '');
    //必须保证第一个为数字而不是.
    //obj.value = obj.value.replace(/^\./g, '');

    //价格不能是0 所以过滤掉第一个0
    obj.value = obj.value.replace(/^0/g, '');

    //保证只有出现一个.而没有多个.
    obj.value = obj.value.replace(/\.{2,}/g, '.');
    //保证.只出现一次，而不能出现两次以上
    obj.value = obj.value.replace('.', '$#$').replace(/\./g, '').replace(
            '$#$', '.');
    //如果第一位是负号，则允许添加
    if (t == '-') {
        obj.value = '-' + obj.value;
    }

    if(obj.value.substr(obj.value.indexOf('.')+1,2)=='00'){
    	obj.value = '';
    }
}

function onlyNumberHaveZero(obj) {
    //得到第一个字符是否为负号
    var t = obj.value.charAt(0);
    //先把非数字的都替换掉，除了数字和.
    obj.value = obj.value.replace(/[^\d\.]/g, '');
    //必须保证第一个为数字而不是.
    obj.value = obj.value.replace(/^\./g, '');


    //保证只有出现一个.而没有多个.
    obj.value = obj.value.replace(/\.{2,}/g, '.');
    //保证.只出现一次，而不能出现两次以上
    obj.value = obj.value.replace('.', '$#$').replace(/\./g, '').replace(
            '$#$', '.');
    //如果第一位是负号，则允许添加
    if (t == '-') {
        obj.value = '-' + obj.value;
    }
}

    // 增加商品属性的js
    $(function () {
        // Stuff to do as soon as the DOM is ready;
        $(document).on("click", ".addrow", function () {
            var addcolumn = "<div class='rowh'><div class='row_name'><input type='text' name='' placeholder='请输入属性名'></div><div class='row_right'><input type='text' name='' placeholder='请输入属性值'></div></div>";
            $(".isjiaruh").append(addcolumn);
            $(".rowh").each(function () {
                if ($(".rowh").length > 10) {
                    $(".addrow").attr("disabled", true);
                    return false;
                }
            });
        });

        // 品牌选择 下拉选择框 根据拼音进行排序
        $(".qxzbrands").click(function () {
            $(".brandsxuanze").show();
        });
        $(".num_name").click(function () {
            var $this = $(this);
            $(".qxzbrands")[0].innerText = $this.text();
            $('#brands').find('input[name="brand_id"]').val($this.data('id'));
            $(".brandsxuanze").hide();
        });

        $(".service").click(function(){
        	 var service ='';
        	    $(".service").each(function(){
        	        if($(this).is(':checked')){
        	            service= service +$(this).val() + ',';
        	        }
        	    });
        	    service = service.substring(0,service.length -1);
        	    $('#after_sale_guarantee').val(service);
         });
		$(".window").click(function(){
			if($(this).is(':checked')){
				$(this).val(1);
			}else{
				$(this).val(0);
			}

		});

        $(".tijiao, .drafts").click(function () {
        	 $('#is_for_sale').val($(this).data('type'));

        	 var custom_attrs ='';
//         	 $(".cpu_type").find('input[name="cattrs"]').each(function(){
//         		  if($(this).is(':checked')){
//         			  custom_attrs= custom_attrs +$(this).attr('data-aid')+":"+$(this).attr('data-aname')+","+$(this).val() + ':'+$(this).attr('data-name')+";";
//       	          }
//              });

        	 $(".cpu_type").find('option[name="cattrs"]').each(function(){
        		  if($(this).is(':selected')){
        			  custom_attrs= custom_attrs +$(this).attr('data-aid')+":"+$(this).attr('data-aname')+","+$(this).val() + ':'+$(this).attr('data-name')+";";
      	          }
             });

             if(custom_attrs){
            	 custom_attrs = custom_attrs.substr(0,custom_attrs.length-1);
             }

             $("#custom_attrs").val(custom_attrs);

        	getAlreadySetSkuVals();
        	var sku_input_num = 0;
            $('.skuTable input[type="text"]').each(function(){
                if($(this).val() == ''){
                    sku_input_num++;
                }
            })
            if (sku_input_num > 0 || $('.skuTable input[type="text"]').length  == 0){
                $("#err_sku").html('请填写商品规格');
                return false;
            } else {
                $("#err_sku").html('');
            }


        });
        var formtype = '{{isset($type)?$type:'POST'}}';
        if (formtype=='put') {
            $("#frm-post").on('submit', function (e) {
                e.preventDefault();
                form = $('#frm-post');
                data = form.serialize();
                url = form.attr('action');
                $.ajax({
                    url: url,
                    type: formtype,
                    data: data,
                    success: function (res) {
                        console.log(res);
                        if (res.code == 0) {
                            layer.confirm('保存成功！点击确认返回商品列表。', {
                                btn: ['确定', '取消'] //可以无限个按钮
                            }, function () {
                                location.href = '/member/seller/product?product_type=1&@if(session('current_page'))page={{session('current_page')}}@endif';
                            }, function (index) {
                                layer.close(index);
                            });
                        } else {
                            layer.alert(res.message, {
                                title: '提示',
                                icon: 2
                            });
                        }
                    },
                    error: function () {
                    }
                });
            });
        }
        var img_type;
        // 图片上传点击
        $('.btn_listimg, .btn_detailimg').click(function () {
            img_type = $(this).attr('data-id');
            if(img_type == 1){
                var _length = $(this).parent().find('.shangchuan').length
                if (_length < 6) {
                    $('.inputFile').trigger('click');
                    $('.inputFile').attr('type','file');
                } else {
                    layer.alert('最多可上传五张商品图', {
                        title:'提示',
                        icon: 2
                    });
                }
            }else{
                $('.inputFile').trigger('click');
                $('.inputFile').attr('type','file');
            }
        });
        $(document).on('mouseover', '.upload-img-item', function () {
            var $this = $(this);
            $this.find('.icon-colse').show();
        }).on('mouseout', '.upload-img-item', function () {
            var $this = $(this);
            $this.find('.icon-colse').hide();
        });
        $(document).on('click', '.icon-colse', function () {
            var $this = $(this), img_name = $this.parent().find('.shangchuan').attr('src');
            $("#frm-post").find('input[class="j-hid-images"]').each(function () {
                if (img_name == $(this).val()){
                    $(this).remove();
                }
            });

            if($this.parent().parent().hasClass("list_image")){
                $(".list_image input[name=cover_image]").val('')
                $this.siblings(".btn_listimg").attr("src",$('.default_img').attr("src"))
                $this.remove()
            }else{
                $this.parent().remove();
            }
        });
        // 选择完要上传的文件后, 直接触发表单提交
        $('input[name=image]').on('change', function () {
            $('.inputFile').attr('type','file');
            if ($.trim($(this).val())) {
                $("#uploadForm").trigger('submit');
            }
            //防止选择同个文件上传不触发该事件
            $(this).val('')
        });

        // 图片上传
        $("#uploadForm").on('submit', function (e) {
            $('.inputFile').attr('type','file');
            //var index=layer.load(2,{shade:[0.1,'#000']})//0.1透明度的黑色背景
            e.preventDefault();
            // $.ajax({
            //     url: "{{url('uploads/images')}}",
            //     type: "POST",
            //     data: new FormData(this),
            //     contentType: false,
            //     cache: false,
            //     processData: false,
            //     // 显示加载图片
            //     success: function (res) {
            //         layer.close(index)
            //         $('.inputFile').attr('type','botton');
            //         if (res.status == 0){
            //             var img_path = '' + res.path;
            //             if(img_type == 0){
            //                 var html = '<div class="upload-img-item"><img src="'+ img_path +'" class="shangchuan" /></div><input type="hidden" name="cover_image" value="'+ img_path +'"/>';
            //                 $(".list_image").html(html);
            //             }else{
            //                 $("#upload-img").parent().prepend('<div class="upload-img-item"><img src="/img/web/user/close.png" class="icon-colse" /><img src="'+ img_path +'" class="shangchuan" /></div>');
            //                 $("#frm-post").append('<input type="hidden" name="images[]" value="'+ img_path +'" class="j-hid-images"/>');
            //             }
            //             layer.alert('图片上传成功', {
            //                 title:'提示',
            //                 icon: 1
            //             });
            //         } else {
            //             layer.alert('图片上传失败', {
            //                 title:'提示',
            //                 icon: 2
            //             });
            //         }
            //     },
            //     error: function () {   layer.close(index) }
            // });
            var cb=function(res){
                var img_path = '' + res.path;
                if(img_type == 0){
                    $(".list_image .shangchuan").attr("src",img_path)
                    $(".list_image input[name=cover_image]").val(img_path)
                    // var html = '<div class="upload-img-item"><img src="'+ img_path +'" class="shangchuan btn_listimg" data-id="0" /></div><input type="hidden" name="cover_image" value="'+ img_path +'"/>';
                    var ele=$(".list_image .upload-img-item")
                    if(ele.find('.icon-colse').length==0){
                        ele.prepend('<img src="/img/web/user/close.png" class="icon-colse" >')
                    }
                }else{
                    $("#upload-img").parent().append('<div class="upload-img-item"><img src="/img/web/user/close.png" class="icon-colse" /><img src="'+ img_path +'" class="shangchuan" /></div>');
                    $("#frm-post").append('<input type="hidden" name="images[]" value="'+ img_path +'" class="j-hid-images"/>');
                }
            }
            //var fc=function(){$('.inputFile').attr('type','botton');}
            uploadFile("{{url('uploads/images')}}",new FormData(this),cb)
        });
        //自定义添加规格
        $(document).on('click', '.add_sku_value', function () {
            var _this = this, val = $(_this).prev().val();
            if(val == ""){
            	  layer.alert('值不能为空', {
                      title:'提示',
                      icon: 2
                  });
            }
//             var html ='<li><label class="fl"><input type="checkbox" class="sku_value" propvalid="111"  propid="22" value="1"/>1</label>'
//                         +'<a class="del_sku_value fl" propvalid="111" data-id="1">删除</a>'
//                         +'</li>';
//                         $(_this).parent().before(html);
//             return false;
            $.ajax({
            	url: "{{url('/member/seller/product/attrval')}}",
                type: "POST",
                data: {'attribute_id':$(_this).attr('data-id'),'value':val},
//                 contentType: false,
//                 cache: false,
//                 processData: false,
                dataType: 'json',
                success: function (res) {
                    $('.inputFile').attr('type','botton');
                    if (res.status == 1){

                        var html ='<li><label class="fl"><input type="checkbox" class="sku_value" propvalid="'+res.data.id+'"  propid="'+res.data.attribute_id+'" value="'+res.data.value+'"/>'+res.data.value+'</label>'
                        +'<a class="del_sku_value fl" propvalid="'+res.data.id+'" data-id="'+res.data.attribute_id+'">删除</a>'
                        +'</li>';
                        $(_this).parent().before(html);
                        layer.alert('添加成功', {
                            title:'提示',
                            icon: 1
                        });
                    } else {
                        layer.alert('添加失败', {
                            title:'提示',
                            icon: 2
                        });
                    }
                },
                error: function () { }
            });
        });
        //自定义删除规格
        $(document).on('click', '.del_sku_value', function () {
            var _this = this, propvalid = $(_this).attr('propvalid'),id = $(_this).attr('data-id');
            layer.alert('确认删除？',{
                  icon: 0
            },function (index) {
//                 $(_this).parent().remove();
//                 layer.close(index);
//                 return false;
                $.ajax({
                	url: "{{url('/member/seller/product/attrdel')}}"+"/"+propvalid,
                    type: "delete",
                    data: {id:propvalid},

                    success: function (res) {
                        $('.inputFile').attr('type','botton');
                        if (res.status == 1){
                            $(_this).parent().remove();
                            layer.alert('删除成功', {
                                title:'提示',
                                icon: 1
                            });
                        } else {
                            layer.alert('删除失败', {
                                title:'提示',
                                icon: 2
                            });
                        }
                    },
                    error: function () { }
                });
                layer.close(index);
            });

        });


    });

    // 限制输入长度
    function words_deal(obj, len) {
        var $this = $(obj);
        var curLength = $this.val().length;
        if (curLength > len) {
            var num = $this.val().substr(0, len);
            $this.val(num);
            $this.parent().find(".maxtitle").show();
        } else {
            $this.parent().find(".textCount").text(len - $this.val().length);
            $this.parent().find(".maxtitle").hide();
        }
    }

    var ue_detail = UE.getEditor('editor_id', { initialFrameWidth: null });
    ue_detail.ready(function() {
        ue_detail.execCommand('serverparam', '_token', '{{ csrf_token() }}'); // 设置 CSRF token.
    });


//获取已经设置的SKU
$(".getSetSkuVal").on("click",function(){
    $("tr[class*='sku_table_tr']").each(function(){
        var propids = $(this).attr("propids");//SKU类型主键
        var propvalids = $(this).attr("propvalids");//SKU值主键
        var propnames = $(this).attr("propnames");//SKU类型主键
        var propvalnames = $(this).attr("propvalnames");//SKU值主键
    });
});



var alreadySetSkuVals = {};//已经设置的SKU值数据

$(function(){
    //sku属性发生改变时,进行表格创建
    $(document).on("change",'.sku_value',function(){
        getAlreadySetSkuVals();//获取已经设置的SKU值
        getSkuVals();
    });
    if($('#skus').val()){
        getDetailsSetSkuVals();
    }

});
function getSkuVals(){
    var b = true;
    var skuTypeArr =  [];//存放SKU类型的数组
    var totalRow = 1;//总行数
    //获取元素类型
    $(".SKU_TYPE").each(function(){
        //SKU类型节点
        var skuTypeNode = $(this).children("li");
        var skuTypeObj = {};//sku类型对象
        //SKU属性类型标题
        skuTypeObj.skuTypeTitle = $(skuTypeNode).attr("sku-type-name");
        //SKU属性类型主键
        var propid = $(skuTypeNode).attr("propid");
        skuTypeObj.skuTypeKey = propid;
        //是否是必选SKU 0：不是；1：是；
        var is_required = $(skuTypeNode).attr("is_required");
        skuValueArr = [];//存放SKU值得数组
        //SKU相对应的节点
        var skuValNode = $(this).next();
        //获取SKU值
        var skuValCheckBoxs = $(skuValNode).find("input[type='checkbox'][class*='sku_value']");
        var checkedNodeLen = 0 ;//选中的SKU节点的个数
        $(skuValCheckBoxs).each(function(){
            if($(this).is(":checked")){
                var skuValObj = {};//SKU值对象
                skuValObj.skuValueTitle = $(this).val();//SKU值名称
                skuValObj.skuValueId = $(this).attr("propvalid");//SKU值主键
                skuValObj.skuPropId = $(this).attr("propid");//SKU类型主键
                skuValueArr.push(skuValObj);
                checkedNodeLen ++ ;
            }
        });
        if(is_required && "1" == is_required){//必选sku
            if(checkedNodeLen <= 0){//有必选的SKU仍然没有选中
                b = false;
                return false;//直接返回
            }
        }
        if(skuValueArr && skuValueArr.length > 0){
            totalRow = totalRow * skuValueArr.length;
            skuTypeObj.skuValues = skuValueArr;//sku值数组
            skuTypeObj.skuValueLen = skuValueArr.length;//sku值长度
            skuTypeArr.push(skuTypeObj);//保存进数组中
        }
    });
    var SKUTableDom = "";//sku表格数据
    //开始创建行
    if(b){//必选的SKU属性已经都选中了
        SKUTableDom += "<table class='skuTable'><tr>";
        //创建表头
        for(var t = 0 ; t < skuTypeArr.length ; t ++){
            SKUTableDom += '<th>'+skuTypeArr[t].skuTypeTitle+'</th>';
        }
        SKUTableDom += '<th width ="70">价格(元)</th><th width ="70">促销价(元)</th><th width ="70">库存数</th><th width ="150">商家编码</th><th width ="70">运费</th>';
        SKUTableDom += "</tr>";
        //循环处理表体
        for(var i = 0 ; i < totalRow ; i ++){//总共需要创建多少行
            var currRowDoms = "";
            var rowCount = 1;//记录行数
            var propvalidArr = [];//记录SKU值主键
            var propIdArr = [];//属性类型主键
            var propvalnameArr = [];//记录SKU值标题
            var propNameArr = [];//属性类型标题
            for(var j = 0 ; j < skuTypeArr.length ; j ++){//sku列
                var skuValues = skuTypeArr[j].skuValues;//SKU值数组
                var skuValueLen = skuValues.length;//sku值长度
                rowCount = (rowCount * skuValueLen);//目前的生成的总行数
                var anInterBankNum = (totalRow / rowCount);//跨行数
                var point = ((i / anInterBankNum) % skuValueLen);
                propNameArr.push(skuTypeArr[j].skuTypeTitle);
                if(0  == (i % anInterBankNum)){//需要创建td
                    currRowDoms += '<td rowspan='+anInterBankNum+'>'+skuValues[point].skuValueTitle+'</td>';
                    propvalidArr.push(skuValues[point].skuValueId);
                    propIdArr.push(skuValues[point].skuPropId);
                    propvalnameArr.push(skuValues[point].skuValueTitle);
                }else{
                    //当前单元格为跨行
                    propvalidArr.push(skuValues[parseInt(point)].skuValueId);
                    propIdArr.push(skuValues[parseInt(point)].skuPropId);
                    propvalnameArr.push(skuValues[parseInt(point)].skuValueTitle);
                }
            }


            var propvalids = propvalidArr.toString();
            var alreadySetSkuPrice = "";//已经设置的SKU价格
            var alreadySetSkuStock = "";//已经设置的SKU库存
            //赋值

            var obj=JSON.parse($('#skus').val())

            if(obj[propvalids]){
                SKUTableDom += '<tr propvalids=\''+propvalids+'\' propids=\''+propIdArr.toString()+'\' propvalnames=\''+propvalnameArr.join(";")+'\'  propnames=\''+propNameArr.join(";")+'\' class="sku_table_tr">'+currRowDoms+'<td><input type="text" class="setting_sku_price" onkeyup="onlyNumber(this)" onblur="onlyNumber(this)" value="'+obj[propvalids].price+'"/></td><td><input type="text" class="setting_sku_originalprice" onkeyup="onlyNumber(this)" onblur="onlyNumber(this)"  value="'+obj[propvalids].sale_price+'"/></td><td><input type="text" class="setting_sku_stock" onkeyup="onlyNumber(this)" onblur="onlyNumber(this)" value="'+obj[propvalids].stock+'"/></td><td><input type="text" class="setting_sku_coding"    value="'+obj[propvalids].seller_code+'"/></td><td><input type="text" class="setting_sku_freight" onkeyup="onlyNumberHaveZero(this)" onblur="onlyNumberHaveZero(this)" value="'+obj[propvalids].freight+'"/></td><input type="hidden" class="setting_sku_id" onkeyup="onlyNumber(this)" onblur="onlyNumber(this)"  value="'+(obj[propvalids].id?obj[propvalids].id:'')+'"/></tr>';
            }else{
                 SKUTableDom += '<tr propvalids=\''+propvalids+'\' propids=\''+propIdArr.toString()+'\' propvalnames=\''+propvalnameArr.join(";")+'\'  propnames=\''+propNameArr.join(";")+'\' class="sku_table_tr">'+currRowDoms+'<td><input type="text" class="setting_sku_price" onkeyup="onlyNumber(this)" onblur="onlyNumber(this)" value=""/></td><td><input type="text" class="setting_sku_originalprice" onkeyup="onlyNumber(this)" onblur="onlyNumber(this)"  value=""/></td><td><input type="text" class="setting_sku_stock" onkeyup="onlyNumber(this)" onblur="onlyNumber(this)" value=""/></td><td><input type="text" class="setting_sku_coding"    value=""/></td><td><input type="text" class="setting_sku_freight" onkeyup="onlyNumberHaveZero(this)" onblur="onlyNumberHaveZero(this)" value=""/></td><input type="hidden" class="setting_sku_id" onkeyup="onlyNumber(this)" onblur="onlyNumber(this)"  value="0"/></tr>';
            }

        }
        SKUTableDom += "</table>";
    }
    $("#skuTable").html(SKUTableDom);
}
//详情skus
function getDetailsSetSkuVals(){
    getSkuVals()
    var skus = JSON.parse($('#skus').val());
    for(var i  in skus){
        $(".setting_sku_price").eq(i).val(skus[i].final_price);
        $(".setting_sku_originalprice").eq(i).val(skus[i].sale_price);
        $(".setting_sku_stock").eq(i).val(skus[i].stock);
        $(".setting_sku_coding").eq(i).val(skus[i].seller_code);
        $(".setting_sku_freight").eq(i).val(skus[i].freight);
        $(".setting_sku_id").eq(i).val(skus[i].id);
    }
}



function getAlreadySetSkuVals(){
    alreadySetSkuVals = {};
    //获取设置的SKU属性值
    $("tr[class*='sku_table_tr']").each(function(){
        var skuPrice = $(this).find("input[type='text'][class*='setting_sku_price']").val();//SKU价格
        var skuOriginalprice = $(this).find("input[type='text'][class*='setting_sku_originalprice']").val();//促销价价格
        var skuStock = $(this).find("input[type='text'][class*='setting_sku_stock']").val();//SKU库存
        var skuCoding = $(this).find("input[type='text'][class*='setting_sku_coding']").val();//SKU商家编码
        var skuFreight = $(this).find("input[type='text'][class*='setting_sku_freight']").val();//SKU运费
        var sku_id = 0;
        if($('#skus').val()){
            sku_id = $(this).find("input[class*='setting_sku_id']").val();//SKU运费
        }

        var attributes = '';
        if(skuPrice || skuStock){//已经设置了全部或部分值
            var propvalids = $(this).attr("propvalids");//SKU值主键集合
            var propids = $(this).attr("propids");
            var propvalnames = $(this).attr("propvalnames");
            var propnames = $(this).attr("propnames");

            var propvalid = propvalids.split(',');
            var propid = propids.split(',');

            var propvalname = propvalnames.split(';');
            var propname = propnames.split(';');

            for(var i = 0;i<propvalid.length;i++){
                //attributes += propid[i]+','+propvalid[i]+';'
                attributes += propid[i]+":"+propname[i]+','+propvalid[i]+":"+propvalname[i]+';'
            }
            attributes = attributes.substring(0, attributes.length -1);
            alreadySetSkuVals[propvalids] = {
                'attributes':attributes,
                "price" : skuPrice,
                "sale_price" : skuOriginalprice,
                "stock" : skuStock,
                "seller_code" : skuCoding,
                "freight" : skuFreight,
                "id": sku_id

            }
        }
    });
    $("#skus").val(JSON.stringify(alreadySetSkuVals));
}
</script>
<script src="{{asset('/js/plugins/jquery-ui/jquery-ui-1.11.4.min.js')}}"></script>
<script src="{{asset('/js/plugins/jquery-ui/jquery-migrate-3.0.0.min.js')}}"></script>
<script type="text/javascript">
//品牌autocomplete
$(function(){
    var brandList=[]
    var labels=[]
    $('.sort_list').children('.num_name').each(function(){
        var key=$(this).text().trim()
        var val=$(this).attr('data-id').trim()
        brandList[key]=val
        // brandList.push({label:$(this).text().trim(),value:$(this).attr('data-id').trim()})
    })
    labels=Object.keys(brandList).sort(function(a,b){
        var str1=makePy(a)[0].toUpperCase()
        var str2=makePy(b)[0].toUpperCase()
        if(str1 < str2 ) return -1
        if(str1 > str2 ) return 1
        return 0
    })// a.localeCompare(b,"zh");纯中文数组按中文排
    var eleBrandName= $('input[name="brand_name"]' )
    var eleBrandId= $('input[name="brand_id"]' )
    eleBrandName.autocomplete({
      minLength: 0,
      source:labels,
      select: function (event, ui) {
            event.preventDefault();
            eleBrandName.val(ui.item.label);//选中文案
            eleBrandId.val(brandList[ui.item.label])
      },
    });
    eleBrandName.on("focus",function(){
        eleBrandName.autocomplete("search", "" );
    })
    eleBrandName.on("blur",function(){
        var id=brandList[eleBrandName.val().trim()]
        if(id){
             eleBrandId.val(id)
        }else{
            eleBrandName.val('')
            eleBrandId.val('')
        }
    })
})
</script>
</body>
</html>